package com.acme.ionio.impl;

import com.acme.ionio.FileCopierClient;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.Socket;

/**
 * @author Gregory Sobko
 */
public class FileCopierClientIO implements FileCopierClient {

    private static Logger logger = Logger.getLogger(FileCopierClientIO.class);

    @Override
    public void copy(File from, String url, int port) throws IOException {
        try(Socket socket = new Socket(url, port);
            DataOutputStream os = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
            BufferedReader serverReader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
            FileInputStream fis = new FileInputStream(from)){
            os.writeLong(from.length());
            byte[] buffer = new byte[65536];
            int bytesRead = 0;
            while ((bytesRead = fis.read(buffer)) != -1){
                os.write(buffer, 0, bytesRead);
                os.flush();
            }
            logger.info(serverReader.readLine());
        }

    }
}
